package com.freemalll.system.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.freemalll.common.core.constant.UserConstants;
import com.freemalll.common.core.utils.StringUtils;
import com.freemalll.system.domain.SysOrganization;
import com.freemalll.system.mapper.SysOrganizationMapper;
import com.freemalll.system.service.ISysOrganizationService;

/**
 * 组织机构 服务层实现
 * 
 * @author freemalll
 */
@Service
public class SysOrganizationServiceImpl implements ISysOrganizationService
{
    @Autowired
    private SysOrganizationMapper organizationMapper;

    /**
     * 查询组织机构信息
     * 
     * @param id 组织机构ID
     * @return 组织机构信息
     */
    @Override
    public SysOrganization selectOrganizationById(String id)
    {
        return organizationMapper.selectOrganizationById(id);
    }

    /**
     * 根据组织名称查询组织机构信息
     * 
     * @param orgName 组织名称
     * @return 组织机构信息
     */
    @Override
    public SysOrganization selectOrganizationByOrgName(String orgName)
    {
        return organizationMapper.selectOrganizationByOrgName(orgName);
    }

    /**
     * 根据组织唯一编码查询组织机构信息
     * 
     * @param orgOnlyCode 组织唯一编码
     * @return 组织机构信息
     */
    @Override
    public SysOrganization selectOrganizationByOrgOnlyCode(String orgOnlyCode)
    {
        return organizationMapper.selectOrganizationByOrgOnlyCode(orgOnlyCode);
    }

    /**
     * 根据父节点ID查询子组织机构
     * 
     * @param parentId 父节点ID
     * @return 组织机构集合
     */
    @Override
    public List<SysOrganization> selectOrganizationByParentId(String parentId)
    {
        return organizationMapper.selectOrganizationByParentId(parentId);
    }

    /**
     * 查询组织机构列表
     * 
     * @param organization 组织机构信息
     * @return 组织机构集合
     */
    @Override
    public List<SysOrganization> selectOrganizationList(SysOrganization organization)
    {
        return organizationMapper.selectOrganizationList(organization);
    }

    /**
     * 新增组织机构
     * 
     * @param organization 组织机构信息
     * @return 结果
     */
    @Override
    public int insertOrganization(SysOrganization organization)
    {
        return organizationMapper.insert(organization);
    }

    /**
     * 修改组织机构
     * 
     * @param organization 组织机构信息
     * @return 结果
     */
    @Override
    public int updateOrganization(SysOrganization organization)
    {
        return organizationMapper.updateById(organization);
    }

    /**
     * 批量删除组织机构
     * 
     * @param ids 需要删除的组织机构ID
     */
    @Override
    public void deleteOrganizationByIds(String[] ids)
    {
        for (String id : ids)
        {
            SysOrganization organization = selectOrganizationById(id);
            if (StringUtils.isNotNull(organization))
            {
                // 检查是否有子节点
                List<SysOrganization> children = selectOrganizationByParentId(id);
                if (children.size() > 0)
                {
                    throw new RuntimeException("存在子组织，不允许删除");
                }
                organizationMapper.deleteById(id);
            }
        }
    }

    /**
     * 删除组织机构信息
     * 
     * @param id 组织机构ID
     * @return 结果
     */
    @Override
    public int deleteOrganizationById(String id)
    {
        SysOrganization organization = selectOrganizationById(id);
        if (StringUtils.isNotNull(organization))
        {
            // 检查是否有子节点
            List<SysOrganization> children = selectOrganizationByParentId(id);
            if (children.size() > 0)
            {
                throw new RuntimeException("存在子组织，不允许删除");
            }
        }
        return organizationMapper.deleteById(id);
    }

    /**
     * 校验组织名称是否唯一
     * 
     * @param organization 组织机构信息
     * @return 结果
     */
    @Override
    public boolean checkOrgNameUnique(SysOrganization organization)
    {
        String id = StringUtils.isNull(organization.getId()) ? "-1" : organization.getId();
        SysOrganization info = organizationMapper.selectOrganizationByOrgName(organization.getOrgName());
        if (StringUtils.isNotNull(info) && !info.getId().equals(id))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验组织唯一编码是否唯一
     * 
     * @param organization 组织机构信息
     * @return 结果
     */
    @Override
    public boolean checkOrgOnlyCodeUnique(SysOrganization organization)
    {
        String id = StringUtils.isNull(organization.getId()) ? "-1" : organization.getId();
        SysOrganization info = organizationMapper.selectOrganizationByOrgOnlyCode(organization.getOrgOnlyCode());
        if (StringUtils.isNotNull(info) && !info.getId().equals(id))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 构建前端所需要树结构
     * 
     * @param organizations 组织机构列表
     * @return 树结构列表
     */
    @Override
    public List<SysOrganization> buildOrganizationTree(List<SysOrganization> organizations)
    {
        List<SysOrganization> returnList = new ArrayList<SysOrganization>();
        List<String> tempList = organizations.stream().map(SysOrganization::getId).collect(Collectors.toList());
        for (SysOrganization organization : organizations)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(organization.getParentId()))
            {
                recursionFn(organizations, organization);
                returnList.add(organization);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = organizations;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysOrganization> list, SysOrganization t)
    {
        // 得到子节点列表
        List<SysOrganization> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysOrganization tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysOrganization> getChildList(List<SysOrganization> list, SysOrganization t)
    {
        List<SysOrganization> tlist = new ArrayList<SysOrganization>();
        Iterator<SysOrganization> it = list.iterator();
        while (it.hasNext())
        {
            SysOrganization n = (SysOrganization) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().equals(t.getId()))
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysOrganization> list, SysOrganization t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }

    /**
     * 构建前端所需要下拉树结构
     * 
     * @param organizations 组织机构列表
     * @return 下拉树结构列表
     */
    @Override
    public List<SysOrganization> buildOrganizationTreeSelect(List<SysOrganization> organizations)
    {
        List<SysOrganization> organizationTrees = buildOrganizationTree(organizations);
        return organizationTrees;
    }
}